<?php
/**
 * Writer na dynamicku tabulku
 * @author Tomas Srna
 * @package bakalarka
 */

class DynamicTableWriter implements Writer
{
	/**
	 * @var DynamicTable $dt		Dynamicka tabulka
	 */
	protected $dv = NULL;
	
	/**
	 * @var Template $t 			Template
	 */
	protected $t = NULL;
	
	/**
	 * V kontruktore nastavime dynamicky pohlad a template
	 */
	public function __construct(DynamicTable $dt, Template $t)
	{
		$this->dt = $dt;
		$this->t = $t;
	}
	
	/**
	 * Vypis dynamickej tabulky
	 */
	public function write()
	{
		if($this->dt->itemCount > 0)
		{
			echo '<table class="grid">';
			echo '<thead>';
			$this->writeHeaders();
			echo '</thead>';
			echo '<tbody>';
			$this->writeRows();
			echo '</tbody>';
			echo '</table>';
		}
		else
			echo '<p>'.L::selected()->noItems.'</p>';
	}
	
	/**
	 * Vypis hlaviciek tabulky
	 */
	public function writeHeaders()
	{
		echo '<tr>';
		foreach ($this->dt->headers as $key => $value) {
			echo '<th><a class="column-header" id="column-'.$key.'" href="#">'.
					$value.'</a> <img class="column-sortimage" src="'.
					APPBASE.'img/blank.gif" alt="" /> </th>';
		}
		
		if(count($this->dt->buttons))
			echo '<th class="options">'.L::selected()->options.'</th>';
		
		echo '</tr>';
	}
	
	/**
	 * Vypis riadkov
	 */
	public function writeRows()
	{
		foreach ($this->dt->data as $value) 
		{
			$this->writeRow($value);
		}
	}
	
	/**
	 * Vypis jedneho riadka
	 */
	public function writeRow($row)
	{
		echo '<tr>';
		foreach ($this->dt->headers as $key => $value)
		{
			if(!array_key_exists($key, $this->dt->writers) ||
				!($this->dt->writers[$key] instanceof Writer))
					echo '<td>'.htmlspecialchars($row->{$key}).'</td>';
			else
			{
				echo '<td>';
				$this->dt->writers[$key]->set($row->{$key})->write();
				echo '</td>';
			}
		}
		
		if(count($this->dt->buttons))
		{
			echo '<td class="options">';
			
			$pkeys = "";
			$c = count($this->dt->primaryKeys);
			foreach ($this->dt->primaryKeys as $key) {
				--$c;
				$pkeys .= "'".urlencode($row->{$key})."'";
				if($c > 0)
					$pkeys .= ",";
			}
			
			foreach($this->dt->buttons as $button)
			{
				$btn = clone $button;
				$btn->setParams($pkeys);
				echo $btn;
			}
			
			echo '</td>';
		}
		echo '</tr>';
	}
}

